import java.util.ArrayList;
import java.util.List;

/**
 * @author 雷明浩
 * @date 2025/6/3 12:00
 */
public class MergeKLists {
    // newcoder 合并k个已排序的链表
    // https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6?tpId=295&tags=&title=&difficulty=0&judgeStatus=0&rp=0&sourceUrl=%2Fexam%2Foj%3FquestionJobId%3D10%26subTabName%3Donline_coding_page
    public ListNode mergeKLists (ArrayList<ListNode> lists) {
        // write code here
        int size = lists.size();
        if (size == 0) {
            return null;
        }
        return merge(lists, 0, size-1);
    }

    private ListNode merge(ArrayList<ListNode> lists, int left, int right) {
        if (left >= right) {
            return lists.get(left);
        }
        int mid = left + (right-left) / 2;
        ListNode leftList = merge(lists, left, mid);
        ListNode rightList = merge(lists, mid+1, right);
        return sort(leftList, rightList);
    }

    private ListNode sort(ListNode head1, ListNode head2) {
        ListNode phead = new ListNode(-1);
        ListNode cur = phead;
        ListNode cur1 = head1;
        ListNode cur2 = head2;
        while (cur1 != null && cur2 != null) {
            if (cur1.val <cur2.val) {
                cur.next = cur1;
                cur1 = cur1.next;
            }else {
                cur.next = cur2;
                cur2 = cur2.next;
            }
            cur = cur.next;
        }
        if (cur1 != null) {
            cur.next = cur1;
        }
        if (cur2 != null) {
            cur.next = cur2;
        }
        return phead.next;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(4);
        head.next.next = new ListNode(5);
        ListNode head2 = new ListNode(0);
        head2.next = new ListNode(2);
        ArrayList<ListNode> lists = new ArrayList<>();
        lists.add(head);
        lists.add(head2);
        MergeKLists mergeKLists = new MergeKLists();
        mergeKLists.mergeKLists(lists);
    }
}